(function($) {
    $.fn.imageResize = function(params) {
        var width = params.width;
        var height = params.height;
        return this.one("load", function() {
            if ($(this).attr('source_width') > 0) {
                var img_width = $(this).attr('source_width');
            } else {
                var img_width = $(this).width();
                $(this).attr({source_width: img_width});
            }

            if ($(this).attr('source_height') > 0) {
                var img_height = $(this).attr('source_height');
            } else {
                var img_height = $(this).height();
                $(this).attr({source_height: img_height});
            }
            var nw = img_width, nh = img_height;
            if ((nw > width) && width > 0) {
                nw = width;
                nh = (width / img_width) * img_height;
            }
            if ((nh > height) && height > 0) {
                nh = height;
                nw = (height / img_height) * img_width;
            }

            if (height > nh) {
                var margin_top_value = (height - nh) / 2;
            } else {
                margin_top_value = 0;
            }
            if (width > nw) {
                var margin_left_value = (width - nw) / 2;
            } else {
                margin_left_value = 0;
            }

            $(this).css({width: nw, height: nh, maxHeight: height, maxWidth: width, marginTop: margin_top_value, marginLeft: margin_left_value});
        }).each(function() {
            if (this.complete) {
                $(this).trigger("load");
            }
        });
    };
})(jQuery);